package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.reggie.bean.AddressBook;
import com.zrrd.reggie.common.BaseContext;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.AddressBookService;
import net.sf.jsqlparser.statement.select.Wait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    @PostMapping
    public R<String> add(@RequestBody AddressBook addressBook){
        addressBook.setUser_id(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.sucess("添加成功");
    }
    @GetMapping("list")
    public R<List<AddressBook>> list(){
        QueryWrapper<AddressBook> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",BaseContext.getCurrentId());
        wrapper.orderByDesc("is_default");
        return R.sucess(addressBookService.list(wrapper));
    }
    @GetMapping("{id}")
    public R<AddressBook> getbyid(@PathVariable Long id){
        AddressBook byId = addressBookService.getById(id);
        return R.sucess(byId);
    }
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        return addressBookService.updateById(addressBook)?R.sucess("修改成功"):R.error("修改失败");
    }
    @DeleteMapping()
    public R<String> delete(Long ids){
        return addressBookService.removeById(ids)?R.sucess("删除成功"):R.error("删除失败");
    }
    @PutMapping("default")
    public R<String> Default (@RequestBody AddressBook addressBook){
        Long id = addressBook.getId();
        AddressBook service = addressBookService.getById(id);
        QueryWrapper<AddressBook> wrapper=new QueryWrapper<>();
        wrapper.eq("is_default",1);
        AddressBook one = addressBookService.getOne(wrapper);
        one.setIsDefault(0);
        addressBookService.updateById(one);
        service.setIsDefault(1);
        addressBookService.updateById(service);
        return R.sucess("修改成功");
    }
    @GetMapping("default")
    public R<AddressBook> selectdefault(){
        QueryWrapper<AddressBook> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",BaseContext.getCurrentId());
        wrapper.eq("is_default",1);
        AddressBook one = addressBookService.getOne(wrapper);
        if (one!=null){
            return R.sucess(one);
        }else {
            return R.error("用户没有默认地址");
        }

    }
}
